//
//  CYBettingView.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/8/30.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CYBettingView.h"
#import "CYTableView.h"
#import "CYRuleView.h"
#import "CYBettingHeaderView.h"
#import "CYBettingCell.h"
#import "CYBettingWay.h"
#import "CYBettingNumber.h"
#import "CYTime.h"
@interface CYBettingView()<CYTableViewDelegate, CYTableViewDataSource>{
    bettingBlock _myBlock;
    bettingRefreshBlock _refreshBlock;
    bettingHeaderBlock _headerBlock;
}
@property (nonatomic, strong) CYRuleView *ruleView;//投注规则说明
@property (nonatomic, strong) CYLabel *timeLBL;//距离开奖倒计时
@property (nonatomic, strong) CYTableView *cy_tableview;
@property (nonatomic, copy) NSString *date;//开奖日期
@property (nonatomic, assign) NSUInteger time;//开奖倒计时
@property (nonatomic, strong) NSArray *cell_Arr;//彩票位级数组
@property (nonatomic, strong) NSArray *numbers;//彩票的可选择号码数组
@property (nonatomic, strong) NSMutableArray *selectNumArr;//选中的号码
@property (nonatomic, assign) CGFloat cellHeight;//每行的高度
@property (nonatomic, strong) CYBettingHeaderView *sectionHeaderView;//头视图
@property (nonatomic, strong) CYTime *timer;

@end
@implementation CYBettingView
- (instancetype)initWithColor:(UIColor *)color block:(bettingBlock)block refresh:(bettingRefreshBlock)refresh headerBlock:(bettingHeaderBlock)headerBlock{
    self = [super initWithColor:color];
    if (self) {
        _reset = NO;
        _myBlock = block;
        _refreshBlock = refresh;
        _headerBlock = headerBlock;
        self.frame = CGRectMake(0.0, 0.0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIBAR_HEIGHT - STATUS_HEIGHT - 50);
    }
    return self;
}

- (NSMutableArray *)selectNumArr{
    if (!_selectNumArr)
        _selectNumArr = [NSMutableArray array];
    return _selectNumArr;
}

- (CYTime *)timer{
    if (!_timer)
        _timer = [[CYTime alloc]init];
    return _timer;
}

- (CYLabel *)timeLBL{
    if (!_timeLBL) {
        _timeLBL = [[CYLabel alloc]initWithText:@"距离-期截止:00:00" size:13 textcolor:ColorHex(0XFF5B05)];
        [self addSubview:_timeLBL];
        
        [_timeLBL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.mas_top).with.offset(0);
            make.centerX.equalTo(self);
            make.size.mas_equalTo(_timeLBL.bounds.size);
        }];
    }
    return _timeLBL;
}

- (CYRuleView *)ruleView{
    if (!_ruleView) {
        _ruleView = [[CYRuleView alloc]initWithColor:LINE_COLOR updateBounds:nil];
    }
    return _ruleView;
}

- (CYTableView *)cy_tableview{
    if (!_cy_tableview) {
        _cy_tableview = [[CYTableView alloc]initWithBounds:CGRectMake(0.0, 0.0, SCREEN_WIDTH, self.bounds.size.height - _timeLBL.bounds.size.height) backGroundView:self.ruleView dataSource:self delegate:self];
        [self addSubview:_cy_tableview];
        
        [_cy_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_timeLBL.mas_bottom).with.offset(0);
            make.bottom.equalTo(self.mas_bottom).with.offset(0);
            make.centerX.equalTo(self);
            make.width.mas_equalTo(SCREEN_WIDTH);
        }];
    }
    return _cy_tableview;
}

- (CYBettingHeaderView *)sectionHeaderView{
    if (!_sectionHeaderView) {
        WS(self)
        _sectionHeaderView = [[CYBettingHeaderView alloc]initWithColor:[UIColor whiteColor] block:^(NSString *type) {
            __strong typeof (weakSelf) strongSelf = weakSelf;
            strongSelf->_headerBlock(type);
        }];
    }
    return _sectionHeaderView;
}

- (void)setModel:(CYCurrentBetModel *)model{
    if (_model != model) {
        _model = model;
        self.date = ([model.actionNo length] > 8)?[model.actionNo substringFromIndex:8]:model.actionNo;
        self.time = model.endTime;
        _reset = NO;
        self.numbers = model.codeList;
        self.ruleView.exampleStr = model.example;
        self.ruleView.ruleStr = model.simpleInfo;
        self.cell_Arr = model.cellArr;
    }
}

//彩票的号码
- (void)setNumbers:(NSArray *)numbers{
    if (_numbers != numbers)
        _numbers = numbers;
    if ([CYBettingWay isSelectWeiJiWithIdentifier:_model.playedTpl])//有位级选择的高度
        _cellHeight = (ceil(_numbers.count / 6.0) + 1) * AL(32) + (ceil(_numbers.count / 6.0) + 2) * AL(10) + (AL(32) + AL(10));
    //    _cellHeight = AL(PT(52 + 64 * ceil(_numbers.count / 6.0) + 24 * ceil(_numbers.count / 6.0) + 44 + 40)) + AL(32);
    else//没有位级选择的高度
        _cellHeight = (ceil(_numbers.count / 6.0) + 1) * AL(32) + (ceil(_numbers.count / 6.0) + 2) * AL(10);
    //        _cellHeight = AL(PT(52 + 64 * ceil(_numbers.count / 6.0) + 24 * ceil(_numbers.count / 6.0) + 44 + 40));
}

//开奖日期
- (void)setTime:(NSUInteger )time{
    if (_time != time)
        _time = time;
    self.timeLBL.hidden = NO;
    WS(self)
    [self.timer countDown:time time:^(NSString *newtime) {
        weakSelf.timeLBL.text = [NSString stringWithFormat:@"距离%@期截止:%@",weakSelf.date,newtime];
        [weakSelf.timeLBL mas_updateConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(weakSelf.timeLBL.bounds.size);
        }];
    } complete:^{
        if (_model.endTime)
            _refreshBlock();
    }];
    
}

//彩票位级数组
- (void)setCell_Arr:(NSMutableArray *)cell_Arr{
    if (_cell_Arr != cell_Arr)
        _cell_Arr = cell_Arr;
    self.cy_tableview.hidden = NO;
    _cy_tableview.backViewHeight = _ruleView.bounds.size.height;
    [_cy_tableview reloadData];
    
}

//随机号码
- (void)setRandomArr:(NSMutableArray *)randomArr{
    if (_randomArr != randomArr)
        _randomArr = randomArr;
    _reset = NO;
    [_cy_tableview reloadData];
    
}

//购彩车的多少组彩票
- (void)setShopNum:(int)shopNum{
    if (_shopNum != shopNum)
        _shopNum = shopNum;
    _sectionHeaderView.shopNum = shopNum;
    
}

//强制清零
- (void)setReset:(BOOL)reset{
    if (_reset != reset)
        _reset = reset;
    if (_reset) {
        [_randomArr  removeAllObjects];
        _numbers = [NSArray arrayWithArray:_model.codeList];
        [_cy_tableview reloadData];
    }
}

# pragma - mark CYTableViewDataSource Methods
- (NSInteger)numberOfSectionsInCYTableView:(UITableView *)cy_tableView{
    return 1;
}

- (NSInteger)cy_tableView:(UITableView *)cy_tableView numberOfRowsInSection:(NSInteger)section{
    if (_cell_Arr.count * _cellHeight + AL(44) < self.bounds.size.height)
        return ceil((self.bounds.size.height - AL(44)) /_cellHeight);
    else
        return _cell_Arr.count;
}
static NSString *null_cell_identifier = @"null_cell";
- (UITableViewCell *)cy_tableView:(UITableView *)cy_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row >= _cell_Arr.count) {
        UITableViewCell *cell =[cy_tableView dequeueReusableCellWithIdentifier:null_cell_identifier];
        if(!cell){
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:null_cell_identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        return cell;
        
    }
    else{
        NSString *identifyCell = [NSString stringWithFormat:@"CYBettingCell%lu%lu",(long)indexPath.section,indexPath.row];
        CYBettingCell * cell = [cy_tableView dequeueReusableCellWithIdentifier:identifyCell];
        if(!cell)
            cell = [[CYBettingCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifyCell];
        cell.selectWeiJiArr = [CYBettingWay selectWeiJiArr:_model.playedTpl];
        cell.selectWeiJi = [CYBettingWay isSelectWeiJiWithIdentifier:_model.playedTpl];
        cell.specialLottery = [CYBettingWay isSpecialLottery:_model.playedTpl];
        cell.left_title = _cell_Arr[indexPath.row];
        if ([cell.left_title isEqualToString:@"不同号"])
            cell.numberArr = @[@"1",@"2",@"3",@"4",@"5",@"6"];
        else
            cell.numberArr = _numbers;
        if (_randomArr.count > 0 && !cell.selectWeiJi && !cell.specialLottery){//没有位级的随机数组赋值  非特殊玩法
            id random = _randomArr[indexPath.row];
            if ([random isKindOfClass:[NSArray class]])
                cell.randomNum = random;
            else if ([random isKindOfClass:[NSSet class]])
                cell.randomNum = [random allObjects];
            else if ([random isKindOfClass:[NSDictionary class]]){
                if ([_model.playedTpl isEqualToString:@"k3_2dx"]) {
                    NSString *key1 = [[_randomArr[0] allKeys] firstObject];
                    cell.randomNum = ([cell.left_title isEqualToString:key1])?[[[_randomArr[0] allValues] firstObject] allObjects]:[[[_randomArr[1] allValues] firstObject] allObjects];
                }
                else
                    cell.randomNum = [[random valueForKey:[random allKeys][0]] allObjects];
                
            }
        }
        else if (_randomArr.count > 0 && cell.specialLottery){//特殊的玩法，多行cell,只需一行cell选中号码就能投注
            [cell selectNumberBtn:5];
            for (NSDictionary *dict in _randomArr) {
                NSString *leftTitle = [[dict allKeys] firstObject];
                if ([leftTitle isEqualToString:cell.left_title])
                    cell.randomNum = [[[dict allValues]firstObject] allObjects];
            }
        }
        else if (_randomArr.count > 0 && cell.selectWeiJi)//有位级的随机数组赋值
            cell.randomNum = _randomArr;
        WS(self)
        cell.selectBlock = ^(NSString *title, NSMutableSet *set) {
            __strong typeof (weakSelf) strongSelf = weakSelf;
            strongSelf->_myBlock(title, set);
            if ([strongSelf.model.playedTpl isEqualToString:@"k3_2dx"]) {//快三-二同单选
                if ([title isEqualToString:@"同号"]) {
                    __weak typeof(CYBettingCell *)diffCell = [cy_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
                    diffCell.anotherSelectArr = [set allObjects];
                }
                else if ([title isEqualToString:@"不同号"]){
                    __weak typeof(CYBettingCell *)diffCell = [cy_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
                    diffCell.anotherSelectArr = [set allObjects];
                }
            }
        };
        return cell;
    }
}
# pragma - mark CYTableViewDelegate Methods
- (CGFloat)cy_tableView:(UITableView*)cy_tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return _cellHeight;
}
- (CGFloat)cy_tableView:(UITableView *)cy_tableView heightForHeaderInSection:(NSInteger)section{
    return AL(44);
}
- (UIView *)cy_tableView:(UITableView *)cy_tableView viewForHeaderInSection:(NSInteger)section{
    return  self.sectionHeaderView;
}
- (void)releaseTimer{
    [self.timer cancel];
}


/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
